import { Component, OnInit } from '@angular/core';
import { MessageService, SelectItem } from 'primeng/api';
import { BaseComponent, Utils, FileUploadInfo, PagedQueryResult, DataEvent } from 'iisp-ng';

import { DataIEService } from '../dataie.service.js';
import { DataImport, DataImportAction, DataImportQueryParam, Node, TableInfo } from '../model.js';

declare var contextPath: string, fileDownloadRoot: string;

@Component({
	selector: 'data-import',
	templateUrl: './import.component.html',
	providers: [DataIEService]
})
export class DataImportComponent extends BaseComponent implements OnInit {
	dataImports = new PagedQueryResult<DataImport>();
	selectedDataImport: DataImport;
	newDataImport: DataImport = new DataImport();
	queryParam: DataImportQueryParam = new DataImportQueryParam();
	dataFileUploadInfo: FileUploadInfo = new FileUploadInfo(".xls, .xlsx, .xlsm");
	nodes: SelectItem[] = new Array();
	loginUser = new Object();
	isApprover = new Object();
	dtlWindowOpened = false;
	currentAction: DataImportAction;
    ietables: TableInfo[];
    selectedTable: TableInfo;
	
	constructor(private dataieService: DataIEService, messageService: MessageService) { 
        super(messageService);
    }

	ngOnInit(): void {
		this.queryParam.toDate = new Date();
		let d = new Date();
		d.setMonth(d.getMonth() - 1);
		this.queryParam.fromDate = d;
        this.dataieService.getTableList().subscribe(rst => this.ietables = rst, err => this.handleError(err));
//		this.getDataImports();
		this.getNodeList();
	}
	getNodeList(): void {
		this.dataieService.getNodeList().subscribe(rst => {
			for (let prop in rst) {
				let nd: SelectItem = {"value": prop, "label": rst[prop]};
				this.nodes.push(nd);
			}
		}, err => this.handleError(err));
	}
	getDataImports(event?: DataEvent): void {
		if (event) {
			this.queryParam.changePage(event);
		}
        if (this.selectedTable){
            this.queryParam.tableName = this.selectedTable.code;
        } else {
            delete this.queryParam.tableName;
        }
		this.dataieService.getDataImports(this.queryParam).subscribe(rst => this.dataImports = rst, err => this.handleError(err));
	}
	importData(): void {
        if ( this.dataFileUploadInfo.uploadedFiles && this.dataFileUploadInfo.uploadedFiles.length > 0 ) {
            this.newDataImport.fileUri = this.dataFileUploadInfo.uploadedFiles[this.dataFileUploadInfo.uploadedFiles.length-1];
        } else {
            this.showWarnKey("select.file.to.import");
            return;
        }
		this.dataieService.importData(this.newDataImport).subscribe(rst => {
			this.dataImports.datas.unshift(rst);
			this.newDataImport = new DataImport();
			if (rst.importState == 'ERROR') {
				this.showErrorKey("err.IISP_DATA_IMP_ERROR");
			}
		}, err => this.handleError(err));
		this.dataFileUploadInfo.reset();
	}
	getImportResultStatistics(di: DataImport): string {
		if (di.importState == 'IMPORTED') {
			let irs = Utils.resolveLocalizedMessage("txt.ImportStateMessage", [String(di.insertCount), String(di.updateCount), String(di.discardCount)]);
			return irs;
		}
		return di.importMessage;
	}
	resolveState(sts: string): string {
		return Utils.resolveLocalizedMessage("ImportState." + sts);
	}
	resolveAction(act: string): string {
		return Utils.resolveLocalizedMessage("ImportAction." + act);
	}
	showDetail(di: DataImport): void {
		this.selectedDataImport = di;
		this.currentAction = new DataImportAction();
		this.dtlWindowOpened = true;
	}
	closeDetail(): void {
		this.dtlWindowOpened = false;
	}
	doImportAction(act: string): void {
		this.currentAction.action = act;
		this.dataieService.dataImportAction(this.selectedDataImport.id, this.currentAction).subscribe(rst => {
			for (let prop in rst) {
				this.selectedDataImport[prop] = rst[prop];
			}
			this.showSuccessKey("msg.operation.success");
		}, err => this.handleError(err));
	}
	rejectImport(): void {
		this.doImportAction("REJECT");
	}
	approveImport(): void {
		this.doImportAction("APPROVE");
	}
	//================= options ===================
	states = [
	        {"value":"","label":this.resolveMessage('txt.All')},
            {"value":"DRAFT","label":this.resolveMessage('ImportState.DRAFT')},
            {"value":"IMPORTED","label":this.resolveMessage('ImportState.IMPORTED')},
            {"value":"ERROR","label":this.resolveMessage('ImportState.ERROR')},
            {"value":"REJECTED","label":this.resolveMessage('ImportState.REJECTED')}
	]
}